package org.hbkj.springbootmybatis.service;

import org.hbkj.springbootmybatis.dao.ShoppingCartDao;
import org.hbkj.springbootmybatis.entity.ShoppingCartDo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class ShoppingCartService {

    private final ShoppingCartDao shoppingCartDao;

    public ShoppingCartService(ShoppingCartDao shoppingCartDao) {
        this.shoppingCartDao = shoppingCartDao;
    }

    // 根据用户ID查询购物车列表（关联商品信息）
    public List<ShoppingCartDo> getCartListByUserId(Integer userId) {
        return shoppingCartDao.selectByUserId(userId);
    }

    // 添加商品到购物车
    @Transactional
    public void addToCart(ShoppingCartDo cartDo) {
        // 检查是否已存在该商品
        List<ShoppingCartDo> existingItems = shoppingCartDao.selectByUserId(cartDo.getUserid());
        for (ShoppingCartDo item : existingItems) {
            if (item.getGoodsid().equals(cartDo.getGoodsid())) {
                // 已存在则更新数量和总价
                item.setQuantity(item.getQuantity() + cartDo.getQuantity());
                item.setTotalamount(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
                shoppingCartDao.updateQuantityAndTotal(item);
                return;
            }
        }
        // 不存在则新增记录
        shoppingCartDao.insert(cartDo);
    }

    // 更新购物车商品数量
    public void updateQuantity(Integer cartId, Integer userId, Integer quantity, Double totalAmount) {
        ShoppingCartDo cartDo = new ShoppingCartDo();
        cartDo.setCartid(cartId);
        cartDo.setUserid(userId);
        cartDo.setQuantity(quantity);
        cartDo.setTotalamount(new BigDecimal(totalAmount));
        shoppingCartDao.updateQuantityAndTotal(cartDo);
    }

    // 删除购物车商品
    public void deleteCartItem(Integer cartId, Integer userId) {
        shoppingCartDao.deleteByCartIdAndUserId(cartId, userId);
    }
}